package com.lzp.customview.wave

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.annotation.ColorInt
import com.utils.SizeUtils

/**
 * @describe:
 * @Author: lixiaopeng
 * @Date: 12/8/20
 *
 * 区间为0 - 100
 *
 */
class VerticalWaveView : View {

    private val linePaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG)

    //默认
    private var lineWidth = 5f//线宽
    private var lineCount = 100//线个数
    private var lineGap = 0f//不设置线间距，计算得到，默认 view宽度 - leftAndRightMargin = 线宽*线个数+ 线间距*（线个数-1）

    private var lineColor = 0xffe60012.toInt()//线的颜色
    private var leftAndRightMargin = 10f

    private val minHeightValue = 2//线最小高度，当value小于此值，直接展示此值代表的高度

    /**
     * Y轴坐标转换参数
     */
    private val minValue = 0
    private val maxValue = 100

    private val data = ArrayList<Int>(lineCount)

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        leftAndRightMargin = SizeUtils.dip2px(context, 15f)
        initPaint()
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        if (lineGap == 0f && w != 0) {
            lineGap = ((w - leftAndRightMargin*2) - lineWidth * lineCount) / (lineCount - 1)
        }
    }

    private fun initPaint() {
        linePaint.style = Paint.Style.STROKE
        linePaint.strokeWidth = lineWidth
        linePaint.strokeCap = Paint.Cap.ROUND//如果不希望圆角，把这行注释掉
        linePaint.color = lineColor
    }

    /**
     * 元素取值范围：最小值[minValue]，最大[maxValue]，注意转换，会按照此比例作图
     */
    fun freshData(data: List<Int>) {
        this.data.clear()
        this.data.addAll(data)
        invalidate()
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.let {
            var startX = leftAndRightMargin
            data.forEach { value ->
                val drawValue= if (value<minHeightValue){
                    minHeightValue
                }else{
                    value
                }
                it.drawLine(startX+lineWidth/2f,(height-height*drawValue/100f)/2f,startX+lineWidth/2f,(height+height*drawValue/100f)/2f,linePaint)
                startX += lineWidth + lineGap
            }
        }
    }

    fun setLineColor(@ColorInt color:Int){
        this.lineColor = color
        linePaint.color = color
    }

    fun setLeftAndRightMargin(leftAndRightMargin:Float){
        this.leftAndRightMargin = leftAndRightMargin
    }
}